<?php

class LoanController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','update','admin','delete','statistic','assignLoan', 'processAssign'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
		{
			// @todo: be removed.
			if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$model->customerId)))
				throw new CHttpException(403,'You do not have permission to view the loan.');
		}
		
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($dealId)
	{
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
			throw new CHttpException(403,'You do not have permission to create loan for the deal.');
		
		$model = new Loan();
		$model->dealId = $dealId;
		$model->securityCountry="Australia";
		if(isset($_POST['Loan']))
		{
			$model->attributes=$_POST['Loan'];
			if($model->save())
				$this->redirect(array('deal/view','id'=>$dealId));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
			throw new CHttpException(403,'You do not have permission to update the loan.');
		

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Loan']))
		{
			$model->attributes=$_POST['Loan'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
			throw new CHttpException(403,'You do not have permission to delete the loan.');
		
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('deal/view','id'=>$model->dealId));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$loanSearch=new LoanSearch();
		if(isset($_GET['LoanSearch']))
			$loanSearch->attributes=$_GET['LoanSearch'];
		
		//if ajax search, render partial to save some speed
		if(isset($_GET['ajax'])&&$_GET['ajax']=='loan-list'){
			$this->widget('zii.widgets.CListView', array(
				'id'=>'loan-list',
				'dataProvider'=>$loanSearch->search(),
				'itemView'=>'_view',
			));
		}elseif(isset($_GET['action'])&&$_GET['action']=='Export Result'){
			$this->_exportResult($loanSearch);
		}else{
			$this->render('index',array(
				'loanSearch'=>$loanSearch,
			));
		}
	}
	
	private function _exportResult($loanSearch){
		$loans=Loan::model()->findAll($loanSearch->createCriteria());
		
		$fields=Loan::model()->attributeLabels();
		unset($fields['customerId']);
		$fields=CMap::mergeArray($fields, array(
			'customer.fileReferenceNo' => 'File Reference No',
			'customer.title' => 'Title',
			'customer.firstName' => 'First Name',
			'customer.lastName' => 'Last Name',
			'customer.consultant' => 'Consultant',
			'customer.otherName' => 'Other Name',
			'customer.gender' => 'Gender',
			'customer.dateOfBirth' => 'Date Of Birth',
			'customer.companyName' => 'Company Name',
			'customer.contactPhone' => 'Contact Phone',
			'customer.contactMobile' => 'Mobile',
			'customer.contactFax' => 'Fax',
			'customer.email' => 'Email',
			'customer.postalAddress' => 'Postal Address',
			'customer.postalSuburb' => 'Postal Suburb',
			'customer.postalPostcode' => 'Postal Postcode',
			'customer.postalState' => 'Postal State',
			'customer.postalCountry' => 'Postal Country',
			'customer.physicalAddress' => 'Physical Address',
			'customer.physicalSuburb' => 'Physical Suburb',
			'customer.physicalPostcode' => 'Physical Postcode',
			'customer.physicalState' => 'Physical State',
			'customer.physicalCountry' => 'Physical Country',
			'customer.BankName' => 'Bank Name',
			'customer.BankAccountNumber' => 'Bank Account Number',
			
			
			'customer.valueStar' => 'Value Star',
			'customer.note' => 'Note',
			'customer.createDate' => 'Create Date',
			//'createUser.fullName' => 'Create User',
			'customer.team.name' => 'Team',
		));
		
		$out = fopen('php://output', 'w');
		
		header("Content-type: application/vnd.ms-excel; charset=UTF-8");
		header("Content-Disposition: attachment; filename=loans_".date('Ymd').".csv" );
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
		header("Pragma: public");
		// export UTF-8 text header
		fputs($out, "\xEF\xBB\xBF");
		fputcsv($out, $fields);
		foreach($loans as $loan){
			if($loan->customer->gender != null)
				$loan->customer->gender = DataUtil::getGender($loan->customer->gender);
			$row=array();
			foreach ($fields as $field=>$label) {
				if(!strpos($field, '.')){
					$row[$field]=$loan->$field;
				}else{
					$parts=split('\\.', $field);//CVarDumper::dump($field);exit;
					$attribute=$parts[0];
					$subAttribute=$parts[1];
					if($loan->$attribute){
						if(isset($parts[2])){
							if($loan->$attribute->$subAttribute){
								$row[$field]=$loan->$attribute->$subAttribute->{$parts[2]};
							}
						}else{
							$row[$field]=$loan->$attribute->$subAttribute;
						}
					}else{
						$row[$field]='';
					}
				}
			}
			fputcsv($out, $row);
		}
		fclose($out);
	}

	/**
	 * Manages all models.
	 */
/*	public function actionAdmin($customerId)
	{
		//check if current user has right to view this customer's info.
		if(!Yii::app()->user->checkAccess('customerInfoView',array('customerId'=>$customerId)))
			throw new CHttpException(403,'You do not have permission to view this customer.');

		$model=new Loan('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Loan']))
			$model->attributes=$_GET['Loan'];
		
		$model->customerId=$customerId;

		$this->render('admin',array(
			'model'=>$model,
		));
	}*/
	
	public function actionStatistic() {
		$loanSearch=new LoanSearch();
		if(isset($_POST['LoanSearch'])){
			$loanSearch->attributes=$_POST['LoanSearch'];
		}
		$criteria=$loanSearch->createCriteria();
		$criteria->select='sum(amount) as totalAmount, avg(amount) as averageAmount,
		max(amount) as maxAmount, min(amount) as minAmount,
		avg(rate) as averageRate, max(rate) as maxRate, min(rate) as minRate,
		avg(pricing) as averagePricing, max(pricing) as maxPricing, min(pricing) as minPricing
		';
		//if(!empty($criteria->with)){
		//	$criteria->join='LEFT JOIN {{customer}} as customer ON customer.id=customerID';
		//}
		$criteria->join = 'LEFT JOIN {{deal}} AS deal ON deal.id = dealId';
		$commandBuilder= Yii::app()->db->getSchema()->getCommandBuilder();
		$command=$commandBuilder->createFindCommand(Loan::model()->getTableSchema(),$criteria);
		$row=$command->queryRow();
		
		$formatter=Yii::app()->format;
		$result=array(
			'totalAmount'=>number_format($row['totalAmount'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'averageAmount'=>number_format($row['averageAmount'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'maxAmount'=>number_format($row['maxAmount'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'minAmount'=>number_format($row['minAmount'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'averageRate'=>number_format($row['averageRate'],4,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'maxRate'=>number_format($row['maxRate'],4,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'minRate'=>number_format($row['minRate'],4,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'averagePricing'=>number_format($row['averagePricing'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'maxPricing'=>number_format($row['maxPricing'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
			'minPricing'=>number_format($row['minPricing'],2,$formatter->numberFormat['decimalSeparator'],$formatter->numberFormat['thousandSeparator']),
		);

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');
		echo CJSON::encode($result);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 * @return Loan an loan model.
	 */
	public function loadModel($id)
	{
		$model=Loan::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
/*	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='loan-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}*/
	
	/**
	 * The temperory functin to assign old loan to a deal.
	 */
	public function actionAssignLoan($dealId)
	{
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
			throw new CHttpException(403,'You do not have permission to add loan to the deal.');
		
		$model=new Loan('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Loan']))
			$model->attributes=$_GET['Loan'];
					
		// limit loan.
		$critetia = new CDbCriteria();
		$critetia->with = 'customer';
		$critetia->condition = 'customer.createUserId = :userId AND dealId IS NULL';
		$critetia->params = array(':userId'=>Yii::app()->user->id);
		
		// limit result by filter.
		if(!empty($model->customerId))
		{
			$names = split(' ', $model->customerId);
			if(count($names) > 1)
			{
				$critetia->condition .= ' AND (customer.firstName LIKE "%'.$names[0].'%"
				 AND customer.lastName LIKE "%'.$names[1].'%")';
			}
			else 
			{		
				$critetia->condition .= ' AND (customer.firstName LIKE "%'.$model->customerId.'%"
				 OR customer.lastName LIKE "%'.$model->customerId.'%")';
			}
		}
		
		if(!empty($model->bank))
		{
			$critetia->condition .= ' AND bank LIKE "%'.$model->bank.'%"';
		}
		
		
		$dataProvider = new CActiveDataProvider('Loan', array(
			'criteria'=>$critetia,
		));
		
		$deal = Deal::model()->findByPk($dealId);
		
		$this->render('assignLoan',array(
			'dataProvider'=>$dataProvider,
			'deal'=>$deal,
			'model'=>$model,
		));
	}
	
	public function actionProcessAssign()
	{	
		if(!isset($_POST['assignedLoans']) || !isset($_POST['dealId'])){
			throw new CHttpException(403,'Informtion is not complete, can not process it!');
		}
		$loanIds=explode(',', $_POST['assignedLoans']);
		$dealId = $_POST['dealId'];
		
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
		{
			throw new CHttpException(403,'You do not have permission to process the loan.');
		}
		
		foreach ($loanIds as $id){
			$loan = $this->loadModel($id);
			$loan->dealId = $dealId;
			if (!$loan->save()) {
				throw new CHttpException(404,'Datebase Error!');
			}
		}
		
		//Return to deal view page.
		$this->redirect(array('deal/view','id'=>$dealId));
	}
}
